var express = require('express');
var router = express.Router();
var Admin = require('./../sql/admin');
var sql = require('./../sql');
var utils = require('./../utils')
var uuid = require('node-uuid');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var salt = bcrypt.genSaltSync(10); // 加密级别
var  checkCode = require('./checkCode.js')
var User = require('./../sql/user');



/**
 * @api {post} /admin 注册页面获取验证码
 * @apiDescription 获取验证码
 * @apiName code
 * @apiGroup code
 * @apiParam {string} tel 参数必填(手机号)
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 * data:{
 * message:'验证码发送成功',
 * code:验证码,
 * tel：tel
 * }
 * data:{
 *  code:'3333',
 *  message:'已注册'
 * }
 * @apiSampleRequest http://localhost:3000/admin
 * @apiVersion 1.0.0
 */

 /**
 * @api {post} /admin/add 验证注册信息
 * @apiDescription  逻辑正确执行注册
 * @apiName  adduser
 * @apiGroup adduser
 * @apiParam {string} tel 参数必填(手机号)  
 * @apiParam {string} password 参数必填(密码) 
 * @apiParam {string} username 参数必填(用户名) 
 * @apiSuccess {json} data
 * @apiSuccessExample {json} Success-Response:
 * data:{
 * message:'验证码发送成功',
 * code:'6666',
 * userid: '唯一标识',
 * token: token
 * }
 * @apiSampleRequest http://localhost:3000/admin/add
 * @apiVersion 1.0.0
 */

router.post('/', (req, res, next) => {
    let { tel} = req.body
    let random = Math.floor(Math.random() * (9999 - 1000)) + 1000
    console.log(tel)
    sql.find(User, { tel }, { _id: 0 }).then(data => {
        if (data.length === 0) {
            sql.find(Admin, { tel }, { _id: 0 }).then(data => {
                if (data.length === 0) {
                    console.log(random)
                    sql.insert(Admin, {
                        tel: tel,
                        code: random
                    }).then(() => {
                        checkCode.sendCode(tel, random).then(() => {
                            console.log('发送成功')
                            res.send({
                                message: '验证码发送成功',
                                code: random,
                                tel: tel
                            })
                        })
                    })
                } else {
                    sql.update(Admin, { tel }, { $set: { code: random } }).then(() => {
                        checkCode.sendCode(tel, random).then(() => {
                            console.log('发送成功')
                            res.send({
                                message: '验证码重新发送成功',
                                code: random,
                                tel: tel
                            })
                        })
                    })
                }
                
            })  
        }
        else {
            res.send({
                code: 3333,
                message:'已注册'
            })
        }
    })
})
router.post('/add', (req, res, next) => {
    let { tel, password ,username} = req.body
    let userid = 'users_' + uuid.v1();
    password = bcrypt.hashSync(password, salt);
    sql.insert(User, { userid, username, password, tel }).then(() => {
        // userid = data[0].userid;
        let token = jwt.sign({ userid }, 'liu', {
          expiresIn: 60*60*24*30
        })
        res.send({
          code: '6666',
          message: '注册成功',
          token: token,
          userid
        })
      })
})
router.post('/find', (req, res, next) => {
    let password = req.body.password
    //防止解密时没有传password给个空的字符
    password = password || ''  
   
    let obj = {}
    if (req.body.tel) {
        obj.tel = req.body.tel
    }
    if (req.body.username) {
        obj.username = req.body.username
    }
    sql.find(User, obj, { _id: 0 }).then((data) => {
        console.log(data)
        if (data.length === 0) {
            res.send({
                code: '0000',
                message:'未注册/或验证错误'
            })
        } else if (bcrypt.compareSync(password, data[0].password)) {
            let userid = data[0].userid 
            let token = jwt.sign({userid }, 'liu', {
            expiresIn: 60*60*24*30
          })
            res.send({
                code:"1010",
                message: '验证通过',
                data,
                token:token
            })
        }
          else {
            res.send({
                code: '1111',
                message: '手机号已存在/或验证错误',
                data
            })
        }
    })
})
router.post('/code', (req, res, next) => {
    let {tel} = req.body
    let random = Math.floor(Math.random() * (9999 - 1000)) + 1000
    checkCode.sendCode(tel, random).then(() => {
        console.log('发送成功')
        res.send({
            message: '验证码发送成功',
            code: random,
            tel: tel
        })
    })
})
router.post('/update', (req, res, next) => {
    let { tel, password } = req.body
    password = bcrypt.hashSync(password, salt);
    sql.update(User, { tel }, { $set: { password: password } }).then(data => {
        res.send({
            code: '1010',
            message: '修改密码成功',
            data:data
        })
    })
})
router.post('/islogin', (req, res, next) => {
    console.log(1)
    const token = req.headers.token
    console.log(token)
    // assert(token,401,'请先登录')
    if (token) {  
        const tokenData = jwt.verify(token, 'liu', (error, decoded) => {
            if (error) {
                console.log(error.message)
                return
            } 
            let { userid } = decoded
            sql.find(User, { userid }, { _id: 0 }).then(data => {
                if (data.length !== 0) {
                    res.send({
                        code: 200,
                        data:data[0],
                        message:'用户已登录'
                 })
             }
         })
        })
    } else {
        res.send({
            code: '404',
            message:'未登录'
        })
    }
    // console.log(tokenData)
    // assert(id,401,'请先登录')
    
    // assert(req.user,401, '请先登录')
    // await next()
  })

router.post('/updateAvatar', (req, res) => {
    let { avatar, userid } = req.body
    console.log(avatar)
    sql.update(User, { userid }, { $set: { avatar: avatar } }).then(() => {
        res.send({
            code:200
        })
    })
})
module.exports = router
